let page = 1;
const pageSize = 9;
const updateObj = {
    "id": "",
    "userName": "",
    "password": "",
    "phone": "",
    "email": ""
};
let table_data = [];

let maxCount;

window.onload = initTable;

// 初始化表格
function initTable() {
    getPageData(1);
}

// 分页查询
function getPageData(num) {
    App.postJson(App.basePath + "/user/page", JSON.stringify({
            "limit": pageSize,
            "orderBys": [
                {
                    "asc": true,
                    "orderField": "createTime"
                }
            ],
            "page": num,
            "param": {
                "status": null,
                "userName": null
            }
        })
        , function (res) {
            table_data = null;
            table_data = res.data;
            maxCount = Math.ceil(res.count / 9);
            changeTable();
        }
        , function (res) {
            clear_updateObj();
        }, function () {

        });
}
//添加用户
function addUserInfo() {
    const emailReg = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/;
    const phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!emailReg.test($("#addEmail").val().trim())) {
        alert("邮箱格式不正确");
        return;
    }
    if (!phoneReg.test($("#addPhone").val().trim())) {
        alert("手机号格式不正确");
        return;
    }
    App.post(App.basePath + "/user/save", {
            id: "0",
            userName: $("#addName").val().trim(),
            password: $("#addPwd").val().trim(),
            phone: $("#addPhone").val().trim(),
            email: $("#addEmail").val().trim()
        },
        function (res) {
            alert("添加成功");
        }
        , function (res) {
            alert("添加失败");
        }, function () {
        });
    return false;
}

//搜索用户
function searchUserInfo() {
    console.log("开始搜索用户信息");
    if ($("#userId").val().trim() == null) {
        return;
    }
    App.get(App.basePath + "/user/get", {"id": $("#userId").val().trim()},
        function (res) {
            // console.log("搜索单个用户成功：" + JSON.stringify(res.data));
            table_data = [res.data];
            // console.log("现在表格数据：" + JSON.stringify(table_data));
            changeTable();
        }, function (res) {
            alert("搜索失败");
        }, function () {
        });
    return false;
}

//首页
function goFirstPage() {
    const elementsByName = document.getElementsByName("pageSpan");
    for (let i = 0; i <elementsByName.length ; i++) {
        elementsByName[i].innerText = i+1;
    }
    page = 1;
    getPageData(page);
}

//尾页
function goEndPage() {
    const elementsByName = document.getElementsByName("pageSpan");
    let maxPage = document.getElementById("maxPage").innerText;
    if(maxCount>maxPage){
        for (let i = 0; i <elementsByName.length ; i++) {
            elementsByName[i].innerText = maxCount+i-elementsByName.length +1;
        }
    }
    page = maxCount;
    getPageData(page);
}

//上下翻页
function up_down_page(flag) {
    if (flag === false) {
        page++;
    } else if (page !== 1) {
        page--;
    }
    page = page >= maxCount ? maxCount : page;
    const elementsByName = document.getElementsByName("pageSpan");
    let minPage = document.getElementById("minPage").innerText;
    let maxPage = document.getElementById("maxPage").innerText;
    if (page > maxPage) {
        for (let i = 0; i < elementsByName.length; i++) {
            elementsByName[i].innerText = parseInt(elementsByName[i].innerText) + parseInt(6);
        }
    }
    if (page < minPage) {
        for (let i = 0; i < elementsByName.length; i++) {
            elementsByName[i].innerText = parseInt(elementsByName[i].innerText) - parseInt(6);
        }
    }
    getPageData(page);
}

//数字键翻页
function goPage(element) {
    page = element.innerText;
    page = page >= maxCount ? maxCount : page;
    getPageData(page);
}

//改变翻页按钮的颜色
function changeButColor() {
    const elementsByName = document.getElementsByName("pageSpan");
    for (let i = 0; i < elementsByName.length; i++) {
        if (elementsByName[i].innerText == page) {
            elementsByName[i].style.backgroundColor = "rgba(29,43,85,0.6)";
        } else {
            elementsByName[i].style.backgroundColor = null;
        }
    }
}

// 改变表格的数据
function changeTable() {
    const tableData = document.getElementById("userInfo");
    $("#userInfo  td:not(:first)").empty("");
    for (var i = 0; i < table_data.length ; i++) {
        tableData.rows[i+1].cells[0].innerHTML = i+1+'';
        tableData.rows[i+1].cells[1].innerHTML = table_data[i].userName;
        tableData.rows[i+1].cells[2].innerHTML = table_data[i].phone;
        tableData.rows[i+1].cells[3].innerHTML = table_data[i].email;
        tableData.rows[i+1].cells[4].innerHTML = table_data[i].createTime;
        tableData.rows[i+1].cells[5].innerHTML = "<img id='" + i + "' class='opSty'   src=\"/images/backgrounds/update.png\" alt=\"\" onclick='updateUser(this)' data-toggle='modal' data-target='#myModal'/>";
        if (table_data[i].status === 1) {
            tableData.rows[i+1].cells[6].innerHTML = "<label class='switch-btn'> " +
                "<input id=" + table_data[i].id + " class='checked-switch' type='checkbox' checked='true' onclick='return changeUserStatus(this)'/>" + "<span id='switch-text' class='text-switch' data-yes='启用' data-no='禁用'></span> \n" +
                "    <span class='toggle-btn'></span> " +
                "</label> ";
        } else {
            tableData.rows[i+1].cells[6].innerHTML = "<label class='switch-btn'> " +
                "<input id=" + table_data[i].id + " class='checked-switch' type='checkbox'  onclick='return changeUserStatus(this)'/>" + "<span id='switch-text' class='text-switch' data-yes='启用' data-no='禁用'></span> \n" +
                "    <span class='toggle-btn'></span> " +
                "</label> ";
        }
    }
    changeButColor();
    clear_updateObj();
}

//改变用户状态
function changeUserStatus(element) {
    if (element.checked === false) {
        console.log("用户为启用，改变状态为禁用，id:" + element.id);
        removeUser(element.id);
    } else {
        console.log("用户为禁用，改变状态为启用，id:" + element.id);
        enableUser(element.id);
    }
}

//启用用户
function enableUser(id) {
    App.post(App.basePath + "/user/enable", {"id": id},
        function (res) {
            // alert(res.msg);
        }
        , function (res) {
            alert("修改失败" + res.msg);
        }, function () {

        });
    getPageData(page);
    return false;
}

//禁用用户
function removeUser(id) {
    App.post(App.basePath + "/user/disabled", {"id": id},
        function (res) {
            // alert(res.msg);
        }
        , function (res) {
            alert("修改失败" + res.msg);
        }, function () {

        });
    getPageData(page);
    return false;
}

// 打开更新用户面板
function updateUser(element) {
    clear_updateObj();
    const tableData = document.getElementById("userInfo");
    updateObj.id = table_data[parseInt(element.id)].id;
    var row=parseInt(element.id)+1;
    document.getElementById("userName").value = updateObj.userName = tableData.rows[row].cells[1].innerHTML;
    document.getElementById("phone").value = updateObj.phone = tableData.rows[row].cells[2].innerHTML;
    document.getElementById("email").value = updateObj.email = tableData.rows[row].cells[3].innerHTML;
}

// 提交数据更新用户
function updateUser_goServer() {
    updateObj.userName = document.getElementById("userName").value;
    updateObj.phone = document.getElementById("phone").value;
    updateObj.email = document.getElementById("email").value;
    updateObj.password = document.getElementById("password").value;
    const emailReg = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/;
    const phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!emailReg.test(updateObj.email)) {
        alert("邮箱格式不正确");
        return;
    }
    if (!phoneReg.test(updateObj.phone)) {
        alert("手机号格式不正确");
        return;
    }
    App.post(App.basePath + "/user/update", updateObj,
        function (res) {
            $('#myModal').modal('hide');
            alert("修改用户信息成功");
            clear_updateObj();
            getPageData(page);
        }
        , function (res) {
            alert("修改失败" + res);
        }, function () {

        });
    return false;
}

//清除更新对象
function clear_updateObj() {
    updateObj.password = "";
    document.getElementById("password").value = null;
}